<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:page="page"
               v-model:search="search"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               :row-class-name="rowClassName"
               :cell-class-name="rowClassName"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="primary" icon="el-icon-plus" v-if="permission.sales_price_add" @click="handleAdd">新 增
        </el-button>
        <el-button
            type="warning"
            icon="el-icon-download"
            @click="handleExport"
        >导出
        </el-button>
      </template>

      <template #activeDate-search="{ disabled, size }">
        <el-date-picker
            size="default"
            style="width:94%"
            v-model="this.activeDateRange"
            type="daterange"
            :format="dateFormat"
            :value-format="dateFormat"
            unlink-panels
            start-placeholder="Start Date"
            end-placeholder="End Date"
            clearable
            placeholder="生效日期"
            @change="handleDatePickerChange"
            :picker-options="pickerOptions"
        >
        </el-date-picker>
      </template>

      <template #price-search="{ disabled, size }">
        <number-range
            v-model="priceRange"
            v-model:min-value="search.priceStart"
            v-model:max-value="search.priceEnd"
            precision="3"
            :valueRange="[0, 99999999]">
        </number-range>
      </template>

      <template #menu="{ row, size, type }">
        <el-tooltip content="查看" placement="top">
          <el-button
              icon="el-icon-view"
              link
              :size="size"
              :type="type"
              @click="() => handleView(row)"
              v-if="permission.sales_price_view"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="修改" placement="top" v-if="row.isAssign=='未审核'">
          <el-button
              icon="Edit"
              link
              :size="size"
              :type="type"
              @click="() => handleEdit(row)"
              v-if="permission.sales_price_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="审核" placement="top" v-if="row.isAssign=='未审核'">
          <el-button
              icon="EditPen"
              link
              :size="size"
              :type="type"
              @click="() => rowAudit(row)"
              v-if="permission.sales_price_audit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="反审核" placement="top" v-if="row.isAssign =='已审核'">
          <el-button
                  icon="NoSmoking"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rollbackAudit(row)"
                  v-if="permission.sales_price_audit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="复制" placement="top">
          <el-button
              icon="DocumentCopy"
              link
              :size="size"
              :type="type"
              @click="() => handleCopy(row)"
              v-if="permission.sales_price_edit"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="修正查询" placement="top">
          <el-button
              icon="List"
              link
              :size="size"
              :type="type"
              @click="() => showLog(row)"
          >
          </el-button>
        </el-tooltip>
        <el-tooltip content="删除" placement="top" v-if="row.isAssign !='已审核'">
          <el-button
                  icon="el-icon-delete"
                  link
                  :size="size"
                  :type="type"
                  @click="() => rowDel(row)"
                  v-if="permission.sales_price_delete"
          >
          </el-button>
        </el-tooltip>
      </template>
    </avue-crud>
    <sales-price-form ref="salesPriceForm" @success="refreshChange" ></sales-price-form>
    <sales-price-log ref="salesPriceLog" ></sales-price-log>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove,audit, changeStatus} from "@/api/anwise/sales/sales_price";
  import {mapGetters} from "vuex";
  import salesPriceForm from "@/views/anwise/sales/components/sales_price_form.vue";
  import salesPriceLog from "@/views/anwise/sales/components/sales_price_log.vue";
  import NProgress from "nprogress";
  import {exportBlob} from "@/api/common";
  import {getToken} from "@/utils/auth";
  import {downloadXls} from "@/utils/util";
  import {dateFormat} from "@/utils/date";
  import {userCompany} from "@/api/anwise/common";

  export default {
    components: {
      salesPriceForm,
      salesPriceLog
    },
    data() {
      return {
        form: {},
        query: {},
        search:{},
        loading: true,
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        activeDateRange:[],
        priceRange: [],
        dateFormat:"YYYY-MM-DD",
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: false,
          searchMenuSpan: 6,
          border: true,
          index: true,
          selection: true,
          reserveSelection:true,
          labelWidth: 150,
          indexWidth:100,
          menuWidth: 230,
          addBtn: false,
          editBtn: false,
          viewBtn: false,
          delBtn: false,
          stripe: true,
          searchIndex: 3,
          searchIcon: false,
          searchLabelWidth:110,
          searchEnter:true,
          column: [
            {
              label: "品牌",
              prop: "programName",
              type:"select",
              filterable:true,
              dicUrl: '/api/blade-anwise/customer_group/select',
              props: {
                label: 'programName',
                value: 'programName',
              },
              dataType: 'string',
              rules: [{
                required: false,
                message: "请选择品牌",
                trigger: "blur"
              }],
              search: true,
              overHidden: true,
              sortable: true,
              width:120,
            },
            {
              label: "品牌分组",
              prop: "programGroup",
              type: "select",
              dicUrl: "/blade-system/dict-biz/dictionary?code=program_group",
              filterable: true,
              props: {
                label: 'dictValue',
                value: 'dictValue',
              },
              dataType: 'string',
              rules: [{
                required: false,
                message: "请选择品牌分组",
                trigger: "blur"
              }],
              search: true,
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "客户条码",
              prop: "barCode",
              type: "input",
              search: true,
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "物料编号",
              prop: "materialNo",
              type: "input",
              search: true,
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "物料名称",
              prop: "materialName",
              type: "input",
              search: true,
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "单价/100PCS",
              prop: "price",
              type: "number",
              search: true,
              overHidden: true,
              sortable: true,
              width:150
            },
            {
              label: "生效日期",
              prop: "activeDate",
              type: "date",
              format: "YYYY年MM月DD日",
              valueFormat: "YYYY-MM-DD",
              search: true,
              overHidden: true,
              sortable: true,
              width:130,
              rules: [{
                required: true,
                message: "请选择生效日期",
                trigger: "blur"
              }],
            },
            {
              label: "是否已审核",
              prop: "isAssign",
              search: true,
              type: "select",
              dicData:[
                {label:"已审核", value:"已审核"},
                {label:"未审核", value:"未审核"}],
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "状态",
              prop: "priceState",
              search: true,
              type: 'select',
              dicData:[
                {label:"有效", value:"有效"},
                {label:"无效", value:"无效"}],
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "贸易条款",
              prop: "tradeTerms",
              type: 'select',
              filterable:true,
              dicUrl: '/api/blade-system/dict-biz/dictionary?code=trade_terms',
              props: {
                label: 'dictValue',
                value: 'dictKey',
              },
              dataType: 'string',
              search: true,
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "币别",
              prop: "rmb",
              search: true,
              type: "select",
              filterable: true,
              overHidden: true,
              sortable: true,
              width:130,
              dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
              props: {
                label: 'dictValue',
                value: 'dictKey',
              },
              dataType: 'string',
            },
            {
              label: "审核人",
              prop: "approver",
              type: "input",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "审核日期",
              prop: "approverDate",
              type: "date",
              valueFormat: 'YYYY-MM-DD',
              format:'YYYY-MM-DD',
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "备注",
              prop: "remark",
              type: "input",
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "创建人员",
              prop: "createUserName",
              type: "input",
              overHidden: true,
              sortable: true,
              width: 150,
            },
            {
              label: "创建日期",
              prop: "createTime",
              valueFormat: 'YYYY-MM-DD',
              format:'YYYY-MM-DD',
              type: "input",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "修改人员",
              prop: "updateUserName",
              type: "input",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              overHidden: true,
              sortable: true,
              width:130
            },
            {
              label: "修改日期",
              prop: "updateTime",
              valueFormat: 'YYYY-MM-DD',
              format:'YYYY-MM-DD',
              type: "input",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              overHidden: true,
              sortable: true,
              width:130
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.sales_price_add, false),
          viewBtn: this.validData(this.permission.sales_price_view, false),
          delBtn: this.validData(this.permission.sales_price_delete, false),
          editBtn: this.validData(this.permission.sales_price_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleCopy(row){
        let title="复制销售单价";
        let type='copy';
        const id = row.id;
        this.$refs.salesPriceForm.show({
          id,
          title,
          type,
          row
        })
      },
      handleExport() {
        // const account = func.toStr(this.search.account);
        // const realName = func.toStr(this.search.realName);
        NProgress.start();
        exportBlob(
            `/blade-anwise/sales_price/export?${this.website.tokenHeader
            }=${getToken()}`, this.search
        ).then(res => {
          downloadXls(res.data, `销售单价${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
          NProgress.done();
        });
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleAdd(){
        let title="创建销售单价";
        let type='edit';
        this.$refs.salesPriceForm.show({
          title,
          type
        })
      },
      handleView(row){
        let title="查看销售单价";
        let type='view';
        const id = row.id;
        this.$refs.salesPriceForm.show({
          id,
          title,
          type
        })
      },
      handleEdit(row){
        let title="编辑销售单价";
        let type='edit';
        const id = row.id;
        this.$refs.salesPriceForm.show({
          id,
          title,
          type
        })
      },
      rowClassName({row, rowindex}) {
        if (row.isAssign ==='未审核') {
          return 'row-yellow';
        }
      },
      rowAudit(row){
        this.loading = true;
        let now = new Date();
        if(row.activeDate<dateFormat(now,"yyyy-MM-dd")){
          this.$message({
            type: "error",
            message: "生效日期不能小于当前日期！"
          });
          this.loading = false;
          return;
        }
        audit(row.id).then(res => {
          if (res.data.success) {
            this.loading = false;
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: res.data.msg || "操作成功!"
            });
          }
        })
      },
      rollbackAudit(row){
        this.loading = true;
        let now = new Date();
        if(row.activeDate<dateFormat(now,"yyyy-MM-dd")){
          this.$message({
            type: "error",
            message: "生效日期小于当前日期不能反审核！"
          });
          this.loading = false;
          return;
        }
        changeStatus(row.id, 2).then(res => {
          this.loading = false;
          if (res.data.success) {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: res.data.msg || "反审核成功!"
            });
          }
        })
      },
      showLog(row) {
        this.$refs.salesPriceLog.show(row.id);
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.priceRange = [];
        this.search.priceStart = '';
        this.search.priceEnd = '';
        this.activeDateRange = [];
        this.search.activeDateStart = '';
        this.search.activeDateEnd = '';
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        console.log(params)
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      handleDatePickerChange(value) {
        console.log(value);
        if (value) {
          this.search.activeDateStart = value[0];
          this.search.activeDateEnd = value[1];
        } else {
          this.search.activeDateStart = '';
          this.search.activeDateEnd = '';
        }
      },
      // handlePriceChange(value) {
      //   console.log(value)
      //   if (value) {
      //     this.search.priceStart = value[0];
      //     this.search.priceEnd = value[1];
      //   } else {
      //     this.search.priceStart = '';
      //     this.search.priceEnd = '';
      //   }
      // },
    }
  };
</script>

<style>
</style>
